import { useState, useEffect } from "react";
import React from "react";
import { useParams } from "react-router-dom";
import { formatDistanceToNow } from "date-fns";
import { zhCN } from "date-fns/locale";
import {
  getQuestionDetailApi,
  ReplyQuestionAnswerApi,
  getReplyAnswerQuestionApi,
  userPostQuestionAnswerApi,
  userDeleteQuestionAnswerApi,
  getQuestionUserCommentListApi,
} from "../../http/module/Question";
import {
  userAddLikesApi,
  userAddFollowApi,
  getUserFollowedApi,
  userDeleteFollowedApi,
  userReplayCommentApi,
} from "../../http/module/User";

// 自定义hooks抽离
function useLikes(initialLikes, id) {
  const [likes, setLikes] = useState(initialLikes);
  const [hasLiked, setHasLiked] = useState(false);

  const handleLike = async () => {
    try {
      const response = await userAddLikesApi(id);
      if (response.code === 200) {
        setLikes((prev) => (hasLiked ? prev - 1 : prev + 1));
        setHasLiked(!hasLiked);
      }
    } catch (error) {
      console.error("Error updating likes:", error);
    }
  };
  return { likes, handleLike, hasLiked };
}
// hooks.js
function useFollow(userId, followedList, onFollowChange) {
  // 直接从传入的Set获取状态
  const isFollowing = followedList.has(userId);
  const [isLoading, setIsLoading] = useState(false);

  const handleFollow = async () => {
    setIsLoading(true);
    try {
      // 先进行乐观更新
      onFollowChange(userId, !isFollowing);

      // 发起真实请求
      const api = isFollowing ? userDeleteFollowedApi : userAddFollowApi;
      const response = await api(userId);

      // 如果请求失败则回滚
      if (response.code !== 200) {
        onFollowChange(userId, isFollowing);
      }
    } catch (error) {
      // 请求失败时回滚
      onFollowChange(userId, isFollowing);
      console.error("关注操作失败:", error);
    } finally {
      setIsLoading(false);
    }
  };

  return {
    isFollowing,
    handleFollow,
    isLoading,
  };
}
//问题描述组件
const QuestionDetailSection = React.memo(
  ({ question, followedList, onFollowSuccess }) => {
    const { isFollowing, handleFollow } = useFollow(
      question.userId,
      followedList,
      onFollowSuccess
    );
    return (
      <div className="bg-white shadow-lg rounded-lg p-6 mb-8">
        <div className="flex gap-4">
          {/* 左侧用户信息 */}
          <div className="w-48 flex flex-col items-center p-4 border-r border-gray-200">
            <UserProfile
              username={question.username}
              avatar={question.avatar}
              time={question.createTime}
              onFollow={handleFollow}
              isFollowing={isFollowing} // 确保属性名正确
            />
          </div>

          {/* 右侧内容区域 */}
          <div className="flex-1 min-w-0">
            <h1 className="text-3xl font-bold mb-3 text-gray-800">
              {question.title}
            </h1>
            <div className="prose max-w-none text-gray-700 mb-4">
              {question.description}
            </div>

            {/* 底部时间信息 */}
            <div className="mt-8 pt-3 border-t border-gray-100 text-sm text-gray-500">
              创建时间: {formatDistanceToNow(new Date(question.createTime))} ago
              {question.updateTime && (
                <span className="ml-4 ">
                  最后编辑: {formatDistanceToNow(new Date(question.updateTime))}{" "}
                  ago
                </span>
              )}
            </div>
          </div>
        </div>
      </div>
    );
  }
);
// 用户信息组件
const UserProfile = React.memo(
  ({ username, avatar, time, onFollow, isFollowing }) => {
    return (
      <div className="w-48 flex flex-col items-center p-4 border-r border-gray-200">
        <img
          src={avatar || "/default-avatar.png"}
          className="w-16 h-16 rounded-full mb-3"
          alt="用户头像"
        />
        <div className="text-center">
          <p className="font-medium text-gray-900">{username}</p>
          <p className="text-sm text-gray-500 mt-1">
            {formatDistanceToNow(new Date(time))} ago
          </p>

          <button
            onClick={onFollow}
            className="text-blue-600 text-sm hover:underline mb-4"
          >
            {isFollowing ? "取消关注" : "关注他"}
          </button>
        </div>
      </div>
    );
  },
  (prevProps, nextProps) => {
    // 仅在关注状态变化时重渲染
    return prevProps.isFollowing === nextProps.isFollowing;
  }
);

const Comment = React.memo(
  ({
    data,
    currentUser,
    onFollowChange,
    onDelete,
    level = 0,
    followedList,
    replayList,
    questionId,
    answerId,
  }) => {
    const { isFollowing, handleFollow, isLoading } = useFollow(
      data.userId,
      followedList,
      (userId, status) => onFollowChange(userId, status)
    );
    const [isExpanded, setIsExpanded] = useState(false); // 默认折叠
    const maxVisibleReplies = 2; // 所有层级统一显示2条后折叠
    const totalReplies =
      replayList?.filter((r) => r.answerId === data.id).length || 0;
    const shouldCollapse = totalReplies > maxVisibleReplies;
    const visibleReplies =
      shouldCollapse && !isExpanded
        ? replayList
            .filter((r) => r.answerId === data.id)
            .slice(0, maxVisibleReplies)
        : replayList.filter((r) => r.answerId === data.id);
    const [showReplyBox, setShowReplyBox] = useState(false);
    const [replyContent, setReplyContent] = useState("");
    const { likes, handleLike, hasLiked } = useLikes(data.likeCount, data.id);
    // 组合回复操作函数
    const onReply = () => {
      // 切换回复框显示状态
      setShowReplyBox((prev) => !prev);
      // 自动滚动到回复区域（可选）
      if (!showReplyBox) {
        setTimeout(() => {
          const element = document.getElementById(`reply-box-${data.id}`);
          element?.scrollIntoView({ behavior: "smooth" });
        }, 100);
      }
    };
    const handleSubmitReply = async () => {
      if (!replyContent.trim()) return;
      try {
        const response = await userReplayCommentApi({
          content: replyContent,
          questionId: questionId,
          answerId: answerId,
        });
        if (response.code === 200) {
          setReplyContent("");
          setShowReplyBox(false);
          onReply(); // 触发父组件刷新数据
        }
      } catch (error) {
        console.error("回复提交失败:", error);
      }
    };
    return (
      <div
        className={`group pl-2 ${
          level > 0 ? "border-l-2 border-gray-100" : ""
        }`}
      >
        <div className="flex gap-3 p-3 hover:bg-gray-50 rounded-lg transition-colors">
          {/* 用户头像 */}
          <div className="flex-shrink-0">
            <div className="w-10 h-10 rounded-full bg-gradient-to-br from-blue-400 to-purple-500 flex items-center justify-center text-white font-medium">
              {data.avatar ? (
                <img src={data.avatar} className="rounded-full" alt="avatar" />
              ) : (
                data.username?.[0] || "?"
              )}
            </div>
          </div>

          {/* 评论内容区域 */}
          <div className="flex-1 min-w-0">
            {/* 用户信息行 */}
            <div className="flex items-center gap-2 mb-1">
              <span className="font-medium text-gray-800">{data.username}</span>
              {data.isUp && (
                <span className="px-2 py-0.5 bg-pink-100 text-pink-600 text-xs rounded-full">
                  UP主
                </span>
              )}
              <span className="text-sm text-gray-500">
                {formatDistanceToNow(new Date(data.createTime), {
                  addSuffix: true,
                  locale: zhCN,
                })}
              </span>
              {level === 0 && (
                <button
                  onClick={handleFollow}
                  disabled={isLoading}
                  className="text-blue-600 text-sm hover:underline ml-2"
                >
                  {isFollowing ? "取消关注" : "关注他"}
                </button>
              )}
            </div>
            {/* 评论内容 */}
            <p className="text-gray-800 mb-2 leading-relaxed">{data.content}</p>

            {/* 操作按钮 */}
            <div className="flex items-center gap-4 text-sm text-gray-500">
              <div className="flex items-center gap-4 text-sm text-gray-500">
                <button
                  onClick={handleLike}
                  className={`flex items-center gap-1 hover:text-blue-500 transition-colors ${
                    data.likeCount ? "text-blue-500" : ""
                  }`}
                >
                  <svg
                    className={`w-4 h-4 transition-transform ${
                      data.likeCount ? "fill-current scale-110" : ""
                    }`}
                    viewBox="0 0 24 24"
                  >
                    <path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z" />
                  </svg>
                  {data.likeCount}
                </button>
              </div>
              <button
                onClick={() => {
                  onReply(data.id);
                  setShowReplyBox(!showReplyBox);
                }}
                className="hover:text-blue-500"
              >
                回复
              </button>
              {data.userId === currentUser && (
                <button
                  onClick={() => onDelete(data.id)}
                  className="hover:text-red-500 replay-button"
                >
                  删除
                </button>
              )}
            </div>
            {/* 回复输入框 */}
            {showReplyBox && (
              <div className="mt-4 flex gap-2">
                <textarea
                  value={replyContent}
                  onChange={(e) => setReplyContent(e.target.value)}
                  className="flex-1 border rounded-lg p-2 text-sm focus:ring-2 focus:ring-blue-300"
                  rows="2"
                  placeholder="写下你的回复..."
                />
                <div className="flex flex-col gap-2">
                  <button
                    className="px-3 py-1.5 bg-blue-500 text-white rounded text-sm hover:bg-blue-600"
                    onClick={handleSubmitReply}
                  >
                    提交
                  </button>
                  <button
                    className="px-3 py-1.5 text-gray-500 text-sm hover:bg-gray-100 rounded"
                    onClick={() => setShowReplyBox(false)}
                  >
                    取消
                  </button>
                </div>
              </div>
            )}
            {/* 回复列表 */}

            {visibleReplies.length > 0 && (
              <div className="mt-4 space-y-4">
                <div className={`space-y-4 ${!isExpanded ? "opacity-90" : ""}`}>
                  {visibleReplies?.map(
                    (reply) =>
                      reply.answerId === data.id && (
                        <Comment
                          key={reply.id}
                          data={reply}
                          questionId={questionId}
                          answerId={answerId}
                          level={level + 1}
                          currentUser={currentUser}
                          followedList={followedList}
                          replayList={replayList.filter(
                            (r) => r.answerId === reply.id
                          )}
                        />
                      )
                  )}
                </div>
                {/* 折叠控制 */}
                {shouldCollapse && (
                  <button
                    onClick={() => setIsExpanded(!isExpanded)}
                    className="text-sm text-blue-500 hover:text-blue-600 flex items-center gap-1"
                  >
                    <svg
                      className={`w-4 h-4 transform ${
                        isExpanded ? "rotate-180" : ""
                      }`}
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M19 9l-7 7-7-7"
                      />
                    </svg>
                    {isExpanded
                      ? "收起回复"
                      : `展开全部 ${totalReplies - maxVisibleReplies} 条回复`}
                  </button>
                )}
              </div>
            )}
          </div>
        </div>
      </div>
    );
  },
  (prevProps, nextProps) => {
    prevProps.followedList === nextProps.followedList &&
      prevProps.data.id == nextProps.data.id;
  }
);
//提交答案组件
const PostAnswer = React.memo(
  ({ onSubmit, questionPostUserId, questionId }) => {
    const [newAnswer, setNewAnswer] = useState("");
    const handleSubmit = async () => {
      if (!newAnswer.trim()) return;
      onSubmit(newAnswer, questionPostUserId, questionId);
      setNewAnswer("");
    };

    return (
      <div className="bg-white shadow-lg rounded-lg p-6">
        <h2 className="text-2xl font-semibold mb-4 text-gray-800">你的回答</h2>
        <textarea
          className="w-full border border-gray-300 rounded-md p-2 mb-4 focus:ring-2 focus:ring-blue-400"
          rows="6"
          placeholder="输入你的回答..."
          value={newAnswer}
          onChange={(e) => setNewAnswer(e.target.value)}
          onKeyDown={(e) => e.ctrlKey && e.key === "Enter" && handleSubmit()}
        />
        <button
          className="bg-blue-500 hover:bg-blue-600 text-white font-medium px-4 py-2 rounded"
          onClick={handleSubmit}
        >
          提交回答
        </button>
      </div>
    );
  }
);
// 主组件
export default function QuestionDetailPage() {
  const { id } = useParams();
  const [question, setQuestion] = useState(null);
  const [answers, setAnswers] = useState([]);
  const [newAnswer, setNewAnswer] = useState("");
  const [loading, setLoading] = useState(true);
  const [replayList, setReplayList] = useState([]);
  // 改为使用Set数据结构
  const [followedList, setFollowedList] = useState(new Set());
  // 优化后的刷新函数
  const refreshFollowedList = async () => {
    try {
      const response = await getUserFollowedApi();
      if (response.code === 200) {
        // 转换为Set结构
        setFollowedList(new Set(response.data.map((item) => item.followerId)));
      }
    } catch (error) {
      console.error("刷新关注列表失败:", error);
    }
  };

  // 添加本地状态更新函数
  const updateFollowStatus = (userId, isFollowing) => {
    setFollowedList((prev) => {
      const newSet = new Set(prev);
      isFollowing ? newSet.add(userId) : newSet.delete(userId);
      return newSet;
    });
  };

  //刷新关注列表函数
  useEffect(() => {
    refreshFollowedList();
  }, []);
  //getQuestionDetailApi
  //getReplyAnswerQuestionApi
  useEffect(() => {
    const fetchData = async () => {
      try {
        const [questionRes, answersRes] = await Promise.all([
          getQuestionDetailApi(id),
          getReplyAnswerQuestionApi(id),
        ]);
        if (questionRes.code === 200) {
          setQuestion({
            ...questionRes.data,
            description: questionRes.data.content,
            username: questionRes.data.username,
            userId: questionRes.data.userId,
          });
        }
        if (answersRes.code === 200) {
          setAnswers(answersRes.data.records);
        }
      } catch (error) {
        console.error("Error fetching data:", error);
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, [id]);
  // 使用 Promise.all + 函数式更新
  const fetchAllReplies = async () => {
    try {
      // 1. 并行发起所有请求
      const requests = answers.map((answer) =>
        getQuestionUserCommentListApi(answer.id)
      );
      // 2. 等待所有请求完成
      const responses = await Promise.all(requests);
      // 3. 合并有效数据
      const allReplies = responses.reduce((acc, res) => {
        if (res.code === 200 && res.data?.records) {
          return [...acc, ...res.data.records];
        }
        return acc;
      }, []);
      setReplayList(allReplies);
    } catch (error) {
      console.error("请求失败:", error);
    }
  };
  // 在获取答案后调用
  useEffect(() => {
    if (answers.length > 0) {
      fetchAllReplies();
    }
  }, [answers]);
  //提交问题函数
  const handlePostAnswer = async (content, questionPostUserId, questionId) => {
    if (!content.trim()) return;
    if (window.localStorage.getItem("currentUserName") === questionPostUserId) {
      alert("你不能回答自己的问题");
      return;
    }
    try {
      const response = await userPostQuestionAnswerApi({
        questionId,
        content,
      });
      if (response.code === 200) {
        setNewAnswer("");
        // 更新答案列表
        getReplyAnswerQuestionApi(id).then((answersRes) => {
          setAnswers(answersRes.data.records);
        });
      }
    } catch (error) {
      console.error("Error posting answer:", error);
    }
  };
  const handleFollowChange = (userId, newStatus) => {
    setFollowedList((prev) => {
      const newSet = new Set(prev);
      newStatus ? newSet.add(userId) : newSet.delete(userId);
      return newSet;
    });
  };
  if (loading) return <div>Loading...</div>;
  if (!question) return <div>Question not found</div>;
  return (
    <div className="min-h-screen bg-gray-100 py-6">
      <div className="max-w-5xl mx-auto px-4">
        <div className="flex justify-between items-center mb-6">
          <button
            className="text-blue-500 hover:text-blue-600"
            onClick={() => window.history.back()}
          >
            ← 返回
          </button>
        </div>
        {question && (
          <QuestionDetailSection
            onFollowChange={handleFollowChange}
            key={question.userId}
            onFollowSuccess={refreshFollowedList}
            question={question}
            followedList={followedList}
          />
        )}
        <div className="mb-8">
          <h2 className="text-2xl font-semibold mb-4 text-gray-800">
            {answers.length} 个回答
          </h2>
          {answers.map((answer) => (
            <Comment
              data={answer}
              key={answer.id}
              answerId={answer.id}
              replayList={replayList}
              currentUser={window.localStorage.getItem("currentUserName")}
              onFollowChange={updateFollowStatus}
              followedList={followedList}
              questionId={id}
            />
          ))}
        </div>
        {/* 提交答案组件 */}
        <PostAnswer
          key={question.id}
          questionPostUserId={question.userId}
          questionId={question.id}
          onSubmit={handlePostAnswer}
        />
      </div>
    </div>
  );
}
